let pickStatus = false; // 是否采集的状态
let dataList = [];

/**
 * 修改开始 暂停按钮状态
 * 按钮文字代表动作，不代表状态
 * @param {HTMLElement} element 按钮元素
 */
function changeStatus(element) {
  if (!$('#room').innerText) {
    return alert('请输入房间号, 进入房间');
  }
  const text = element.textContent;
  if (text.trim() === '开始') {
    element.textContent = '暂停';
    element.classList.add('active');
    pickStatus = true;
  } else {
    element.textContent = '开始';
    element.classList.remove('active');
    pickStatus = false;
    // 暂停以后发送剩余的数据 并清空现有数据
    socket.emit('pick', { userId, room, data: dataList });
    dataList = [];
  }
}

// 初始化采集程序
function initPick() {
  if (window.DeviceMotionEvent) {
    try {
      window.addEventListener('devicemotion', this.handleMotion, false);
    } catch (e) {
      alert('本设备不支持devicemotion' + e.message);
    }
  } else {
    alert('本设备不支持devicemotion');
  }
}

// devicemotion监听事件
// 通过分析y曲线最好
function handleMotion(event) {
  if (!pickStatus) return;
  console.log('#pickStatus: ', pickStatus, event.accelerationIncludingGravity);
  const { x, y, z } = event.accelerationIncludingGravity;
  const data = { x: x.toFixed(1), y: y.toFixed(1), z: z.toFixed(1), time: Date.now() };
  dataList.push(data);
  if (dataList.length >= 20) {
    socket.emit('pick', { userId, room, data: dataList });
    dataList = [];
  }
}

function $(selector) {
  return document.querySelector(selector);
}

// 加入房间
function joinRoom() {
  const roomInput = $('input');
  const room = $('#room');
  const value = roomInput.value;
  if (!value) {
    return alert('请输入房间号');
  }
  initIo(value); // 链接进入房间
  room.textContent = value;

  $('#join-room-wrap').style.display = 'none';
  $('#joined-room-wrap').style.display = 'block';
}

window.onload = function () {
  initPick();
};
